<template>
  <div>
    <el-form ref="formRef" :model="form" size="small" label-width="60" :show-message="false">
      <el-row :gutter="8">
        <el-col :span="6">
          <el-form-item label="角色名称" prop="roleName">
            <el-input placeholder="请输入" v-model="form.roleName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="el-col-auto">
          <el-form-item>
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <vxe-grid ref="gridRef" v-bind="gridOptions">
      <template #control="{ $rowIndex }">
        <el-popconfirm title="确定要删除吗?" :hide-after="0" @confirm="del($rowIndex)">
          <template #reference>
            <el-button link type="danger">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-popconfirm>
      </template>
    </vxe-grid>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { http } from '@/plugins/axios'
import type { VxeGridInstance, VxeGridProps } from 'vxe-table'
import { GRID_BASE_CONFIG } from '@/plugins/vxe-table'

const form = reactive({
  roleName: ''
})

const gridRef = ref<VxeGridInstance<any>>()

const gridOptions = reactive<VxeGridProps<any>>({
  ...GRID_BASE_CONFIG,
  pagerConfig: {
    currentPage: 1,
    pageSize: 10
  },
  proxyConfig: {
    ajax: {
      query: ({ page }) => {
        return getData(page.currentPage, page.pageSize)
      }
    },
    response: {
      result: 'data',
      total: 'count'
    }
  },
  columns: [
    { type: 'seq', title: '序号', width: 70 },
    { field: 'role_name', title: '角色名称' },
    { field: 'control', title: '操作', width: 100, fixed: 'right', slots: { default: 'control' } }
  ]
})

function getData(page: number, pageSize: number) {
  return new Promise((resolve, reject) => {
    const params = {
      roleName: form.roleName,
      page,
      pageSize
    }
    return http({
      url: '/api/role/getRoleList',
      params
    })
      .then((res: any) => {
        resolve(res)
      })
      .catch(() => {
        reject()
      })
  })
}

function search() {
  const $grid = gridRef.value
  if ($grid) {
    $grid.commitProxy('reload')
  }
}
function reset() {
  form.roleName = ''
}

const del = (index: number) => {
  gridOptions.data?.splice(index, 1)
}
</script>

<style lang="scss" scoped></style>
